package com.m4f.fse.web.application;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.wicket.IRequestTarget;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.calldecorator.AjaxCallDecorator;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.behavior.AbstractAjaxBehavior;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.list.PropertyListView;
import org.apache.wicket.markup.repeater.RefreshingView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.request.target.basic.StringRequestTarget;
import org.apache.wicket.util.value.ValueMap;
import com.m4f.fse.components.impl.GsaSearchEngine;
import com.m4f.fse.service.helper.ifc.IServiceLocator;
import com.m4f.fse.service.helper.impl.StaticServiceLocator;

import org.apache.commons.lang.StringUtils;

public class EnginesHome extends BasePage {
	
	private static final Logger LOGGER = Logger.getLogger(EnginesHome.class.getName());
	private static final long serialVersionUID = 1L;
	/** A global list of all comments from all users across all sessions */
    private List<GsaSearchEngine> engineList;
   
    
	@SuppressWarnings("unchecked")
	public EnginesHome() {
		super();
		engineList = new ArrayList<GsaSearchEngine>();
		for (Iterator<GsaSearchEngine> it = getEngineService().list(GsaSearchEngine.class); it.hasNext(); ) {
			engineList.add(it.next());
		}
		
		add(new Label("message", "Engines home!"));
		add(new NavomaticBorder("navomaticBorder"));
		
		EngineForm engineForm = new EngineForm("engineForm");
		
		/*engineForm.add(new AjaxFormSubmitBehavior(engineForm, "onsubmit") {
            @Override
            protected void onSubmit(AjaxRequestTarget target) {
                // add the list of components that need to be updated
                //target.add(comments);
                //target.add(text);

                // focus the textarea again
                target.appendJavascript("alert('Form submitted');");
            }

            @Override
            protected void onError(AjaxRequestTarget target)
            {
            }
        });*/
		
		add(engineForm);
		
        // Add commentListView of existing comments
		ListView enginesView = new PropertyListView<GsaSearchEngine>("engines", engineList) {
			@Override
			protected void populateItem(final ListItem<GsaSearchEngine> listItem) {
				listItem.add(new Label("priority"));
                listItem.add(new MultiLineLabel("url"));
                listItem.add(new Label("lang"));
                listItem.setOutputMarkupId(true);
                listItem.add(new AjaxLink("delete"){
					private static final long serialVersionUID = 1L;
					@Override
                	public void onClick(AjaxRequestTarget arg0) {
						GsaSearchEngine searchEngine = listItem.getModelObject();
						getEngineService().delete(searchEngine);
						engineList.remove(searchEngine);
                	}
					@Override
					protected IAjaxCallDecorator getAjaxCallDecorator() {
						return new AjaxCallDecorator() {
							private static final long serialVersionUID = 1L;
							public CharSequence decorateScript(CharSequence script) {
						        return "checkOperation('Seguro que desea eliminar el elemento');" + script;
						    }
						    public CharSequence decorateOnSuccessScript(CharSequence script) {
							     return "deleteEngine('" + listItem.getMarkupId() + "'); " +  script;
							}
						};
					}
                });
			}
        };
		add(enginesView).setVersioned(false);
        //encapsulate the ListView in a WebMarkupContainer in order for it to update
        WebMarkupContainer listContainer = new WebMarkupContainer("theContainer");
        listContainer.setOutputMarkupId(true);
        //listContainer.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)));
        // add the list view to the container
        listContainer.add(enginesView);
        // finally add the container to the page
        add(listContainer);
	}
	
	public final class MyAjaxBehaviour extends AbstractAjaxBehavior {
		
		private static final long serialVersionUID = 1L;
		
		@Override
		public void onRequest() {
			 //get parameters
            final RequestCycle requestCycle = RequestCycle.get();
            WebRequest wr=(WebRequest)requestCycle.getRequest();
            HttpServletRequest hsr= wr.getHttpServletRequest() ;
            try {
                BufferedReader br = hsr.getReader();
                String  jsonString = br.readLine();
                if((jsonString==null) || jsonString.isEmpty()) {
                	LOGGER.severe(" no json found");
                } else {
                	LOGGER.info(" json  is :"+ jsonString);
                }
            } catch (IOException ex) {
            	LOGGER.severe(ex.getMessage());
            }
            // json string to retir to the jQuery onSuccess function
            String data="{code:200}";
            LOGGER.info("returning json :"+ data);
            IRequestTarget t = new StringRequestTarget("application/json", "UTF-8", data);
            getRequestCycle().setRequestTarget(t);	
		}
	}
	
	/**
     * A form that allows a user to add a comment.
     */
    public final class EngineForm extends Form<ValueMap> {
        
    	public EngineForm(final String id) {
            // Construct form with no validation listener
            super(id, new CompoundPropertyModel<ValueMap>(new ValueMap()));
            // this is just to make the unit test happy
            setMarkupId(id);
            // Add simple automated spam prevention measure.
            add(new RequiredTextField<String>("url").setType(String.class));
            add(new RequiredTextField<String>("lang").setType(String.class));
        }
    	
        /**
         * Show the resulting valid edit
         */
        @Override
        public final void onSubmit() {
            ValueMap values = getModelObject();
            // check if the honey pot is filled
            if (!StringUtils.isNotBlank((String)values.get("url"))) {
                error("Caught a spammer!!!");
                return;
            }
            if (!StringUtils.isNotBlank((String)values.get("lang"))) {
                error("Caught a spammer!!!");
                return;
            }
            // Construct a copy of the edited comment
            GsaSearchEngine engine = new GsaSearchEngine((String) values.get("url"));
            engine.setPriority(engineList.size() + 1);
            engine.setLang((String)values.get("lang"));
            // Clear out the text component
            getEngineService().put(engine);
            engineList.add(engine);
            values.put("url", "");
            values.put("lang", "");
        }
    }

    /**
     * Clears the comments.
     */
    public  void clear() {
        engineList.clear();
    }
    
}	